package com.draw.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class DrawPolygonServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //禁止页面缓存
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "No-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/JPEG");//设置响应格式为JPEG图片
        //创建一个指定长度的图像
        int width = 360, height = 280;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();//获取用于处理图形上下文的对象
        graphics.setColor(new Color(221, 221, 221));//设置第一个矩形的RGB颜色
        graphics.fillRect(0, 0, 360, 280);//设置实心矩形
//        graphics.setColor(Color.BLACK);//设置颜色
        graphics.setColor(new Color(178, 186, 174));//设置颜色
        //绘制多边形参数说明如下：
        //要绘制多边形的x坐标数组
        //要绘制多边形的y坐标数组
        //要绘制多边形的顶点总数
        int[] x1 = {100, 120, 180, 140, 150, 100, 50, 60, 20, 80};
        int[] y1 = {20, 85, 90, 120, 180, 140, 180, 120, 90, 85};
        int n1 = 10;
        graphics.fillPolygon(x1, y1, n1);
        int[] x2 = {210, 270, 310, 270, 210, 170};
        int[] y2 = {20, 20, 65, 110, 110, 65};
        int n2 = 6;
        graphics.fillPolygon(x2, y2, n2);
        int[] x3 = {180, 220, 260, 240, 260, 220, 180, 200};
        int[] y3 = {120, 140, 120, 160, 200, 180, 200, 160};
        int n3 = 8;
        graphics.setColor(Color.BLACK);
        graphics.drawPolygon(x3, y3, n3);
        graphics.dispose();//释放次图形的上下文以及它使用的所有系统资源
        ImageIO.write(image, "JPEG", resp.getOutputStream());//输出JPEG格式图片到页面
        resp.getOutputStream().flush();//刷新输出流
        resp.getOutputStream().close();//关闭输出流
    }
}
